<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 
 */
class User_model extends MY_Model
{
    private $account_name = '';
    private $lname = null;
    private $fname = null;
    private $store_name = null;
    //private $order_field = 'lname';
    private $order_field = 'account_name';
    private $order_dir = 'ASC';

    private $sortable_fields = array(
        'account_name'=>'account_name',
        'lname'=>'lname',
        'fname'=>'fname',
        'store_name'=>'store_name',
    );

    /**
     * 
     * @param int $user User id
     * @param str $role user role[user|admin|superadmin] like COC rule.
     * @return boolean
     */
    public function has_role( $user, $role )
    {
        $this->db->join( 'user_roles ur', 'users.id = ur.users_id' );
        $this->db->join( 'roles r', 'r.id = ur.roles_id' );
        return $this->get_by( array( 'r.name' => $role, 'ur.users_id' => $user ) );
    }

    /**
     * Get The user roles
     * 
     * @param int $user userId
     * @return array
     */
    public function get_role( $user)
    {
        $this->db->select('ur.roles_id roles_id, ur.id ur_id, ur.users_id users_id');
        $this->db->join( 'user_roles ur', 'users.id = ur.users_id' );
        $this->db->join( 'roles r', 'r.id = ur.roles_id' );
        return $this->get_by( array('ur.users_id' => $user ) );
    }

    /**
     * 
     * @param type $account
     * @param type $startindex
     * @param type $limit
     * @return type
     */
    public function get_users($account, $startindex=0, $limit=20)
    {
        
        $this->db->select('u.*, r.id as rid');
        $this->db->join( 'user_roles ur', 'users.id = ur.users_id' );
        $this->db->join( 'roles r', 'r.id = ur.roles_id' );
        
//        $sql = 'SELECT u.*, r.id as rid '.
//            'FROM `users` u '.
//            'INNER JOIN `user_roles` ur ON `u`.`id` = `ur`.`users_id` '.
//            'INNER JOIN `roles` r ON `r`.`id` = `ur`.`roles_id` '.
//            ''
//                ;
        $likes = array();
        if ($this->fname){
            $likes['fname']=$this->fname;
        }
        if ($this->lname){
            $likes['lname']=$this->lname;
        }
        if ($this->account_name){
            $likes['account_name']=$this->account_name;
        }
        if ($likes){
            $this->db->like($likes);
        }
        
        if ($this->store_name){
            $this->db->where(array('store_name'=>$this->store_name));
        }
        
//        if ($account){
//            $sql += ' WHERE u.account_name LIKE \'%'.$account.'%\' ';
//        }
//        
//        $sql += ' LIMIT '.$startindex.', '.$limit;
//        
        $this->db->order_by($this->get_order_field(),$this->get_order_dir());
        $this->db->get($this->_table)->result();
//        $q = $this->db->query($sql);
//        return ((int)$q->num_rows())?
//            $q->result():array();
    }
    
    public function get_order_dir()
    {
        if ($this->order_dir == 'ASC'){
            return $this->order_dir;
        }else{
            return 'DESC';
        }
        
    }
    public function get_order_field()
    {
        if (isset($this->sortable_fields[$this->order_field])){
            return $this->order_field;
        }else{
            return 'lname';
        }
    }
    
    public function set_order_dir($dir = 'ASC')
    {
        $this->order_dir = $dir;
        return $this;
    }

    public function set_order_field($field = 'lname')
    {
        $this->order_field = $field;
        return $this;
    }
    
    public function set_searchable_fields($fields= array())
    {
        foreach ($fields as $field => $value){
            
            if (isset($this->sortable_fields[$field])){
                $this->$field = $value;
                log_message('debug', 'Searchbale SET: '.$field.' => '.$value);
            }else{
                log_message('debug', 'Searchbale SKIP: '.$field.' => '.$value);
            }
        }
        return $this;
    }
    
    public function get_count_by_search_field($search_fields = array()){

        if ($search_fields){
            if ($search_fields['store_name']){
                $this->db->where(array('store_name'=>$search_fields['store_name']));
            }unset($search_fields);
            
            $this->db->like($search_fields);
            
        }else{
            $likes = array();
            if ($this->fname){
                $likes['fname']=$this->fname;
            }
            if ($this->lname){
                $likes['lname']=$this->lname;
            }
            if ($this->account_name){
                $likes['account_name']=$this->account_name;
            }
            if ($likes){
                $this->db->like($likes);
            }
            if ($this->store_name){
                $this->db->where(array('store_name'=>$this->store_name));
            }

        }  
        return $this->db->count_all_results($this->_table);            
        //return $this->count_by(array($key.' LIKE ' => '%'.$value.'%'));
        
        //return $this->count_all();
        
    }
    
    
    public function get_count($key, $value){
        if ($key && $value){
            return $this->count_by(array($key.' LIKE ' => '%'.$value.'%'));
        }
        return $this->count_all();
        
    }



    /**
     * This could be bad, cause we are doing search on the users tables.
     * 
     * Hope the users dont goes big.
     * 
     * @return array
     */
    public function get_all_store()
    {
        $this->db->select('store_name')
                ->group_by('store_name');
        return $this->db->get($this->_table)
                ->result();

    }
    /**
     * 
     * @param int $index
     * @param int $limit
     * @return type
     */
    public function get_all_user($index=0, $limit=20)
    {
        
        if ($index === null){
            $this->db->select('users.*, r.id as rid, r.name');
        }else{
            $this->db->select('users.*, r.id as rid, r.name');
        }
        
        $this->db->join( 'user_roles ur', 'users.id = ur.users_id' );
        $this->db->join( 'roles r', 'r.id = ur.roles_id' );
        
        $likes = array();
        if ($this->fname){
            $likes['fname']=$this->fname;
        }
        if ($this->lname){
            $likes['lname']=$this->lname;
        }
        if ($this->account_name){
            $likes['account_name']=$this->account_name;
        }
        if ($likes){
            $this->db->like($likes);
        }
        
        log_message('debug', 'LIKES: '.print_r($likes, 1));
        
        if ($this->store_name){
            $this->db->where(array('store_name'=>$this->store_name));
        }
        
        $this->db->order_by($this->get_order_field(),$this->get_order_dir());
        
        if ($index === null)
            return $this->db->get($this->_table)->result();
        else 
            return $this->db->get($this->_table, $limit, $index )->result();
        
        //return $result->result();
        
    }

    /**
     * Get Active/Inactive users
     * 
     * @param int $status User status, 1=Active; 0=Inactive
     * @return type
     */
    public function get_users_status($status)
    {
        $this->db->select('users.*, r.id as rid, r.name');
        
        $this->db->join( 'user_roles ur', 'users.id = ur.users_id' );
        $this->db->join( 'roles r', 'r.id = ur.roles_id' );
        
        if ($status==0){
            $this->db->where(array('status'=>$status)); // Inactive
            $this->db->order_by('account_name','DESC');
        }else{
            $day=60*60*24;
            $month = $day*30;
            $this->db->where(array('last_activity >='=> (time()-$month))); // Inactive
            $this->db->order_by('last_activity','DESC');
        }
        
        return $this->db->get($this->_table)->result();
        
    }

    public function get_dormant_user()
    {
        $this->db->select('users.*, r.id as rid, r.name');
        
        $this->db->join( 'user_roles ur', 'users.id = ur.users_id' );
        $this->db->join( 'roles r', 'r.id = ur.roles_id' );
        
        $day=60*60*24;
        $month = $day*30;
        $this->db->where(array('last_activity <='=> (time()-$month))); // Inactive
        $this->db->order_by('last_activity','DESC');
        
        return $this->db->get($this->_table)->result();
        
    }
    
    
    /**
     * 
     * @param type $field
     * @return type
     */
    public function field_exists( $field )
    {
        return $this->db->field_exists( $field, $this->config->item('user_table', 'acl_auth') );
    }

    
    /**
     * Retrieve all user that currently with the session timeout.
     * 
     * @return array list of users
     */
    public function get_all_active_user(){
        $this->db->select('account_name');
        // I deduct 30min from the time
        return $this->get_many_by('last_activity >=',time()-(60*30)); 

    }
    
    public function get_user($identity, $byuser =false)
    {
        if( !$identity || is_array($identity))
        {
            return false;
        }
//        if ($byuser){
//            return $this->get_by( $this->config->item( 'identity_field', 'acl_auth' ), $identity );
//        }
        //return $this->get_by( $this->config->item( 'identity_field', 'acl_auth' ), $identity );
        return $this->get_by('account_name', $identity );
        
    }
    
    public function check_token( $token )
    {
        return ( $token === $this->reset_code );
    }
    
    /*
     * Locked the user
     */
    public function locked_user($user_id){
        $exp = $this->config->item( 'locked_attempt_exp', 'acl_auth' );
        return $this->update($user_id, 
                array('locked'=> 1,
                    'locked_expired'=>$exp+time(),
                    'session_id' => $this->session->userdata('session_id'),
                    ));
    }
    public function unlocked_user($user_id, $sessionId){
        return $this->update($user_id, 
                array(
                    'locked'=> 0,
                    'locked_expired'=>0,
                    //'login_expired'=>0,
                    ));
        if ($sessionId){
            // Delete the session data.
            $this->db->delete($this->session->sess_table_name,
                    array('session_id' => $sessionId)); 
        }
    }// unlocked_user
                
}